
#include"sylar/http/http.h"
#include"sylar/log.h"
#include<map>
#include "sylar/http/http_parser.h"
#include<stdlib.h>

static sylar::Logger::ptr logger = SYLAR_LOG_ROOT();
const char *request_data = "POST / HTTP/1.1\r\n"
                    "Host: www.baidu.com\r\n"
                    "Content-Length:10\r\n\r\n"
                    "1234567890";

// 测试http的请求和响应格式
void test_request(){
    sylar::http::HttpRequest::ptr req(new sylar::http::HttpRequest);
    req->setHeader("host", "www.baidu.com");
    req->setBody("Hello world");
    req->dump(std::cout)<<std::endl; // 输出成流式
}

void test_response(){
    sylar::http::HttpResponse::ptr res(new sylar::http::HttpResponse);
    res->setHeader("X-X", "asdasd");
    res->setBody("hello world");
    res->setStatus(sylar::http::HttpStatus::BAD_REQUEST);
    res->setClose(false);
    res->dump(std::cout)<<std::endl;
}

// 测试http parser
void test_request_parser(){
    sylar::http::HttpRequestParser rq_parser;
    std::string tmp = request_data;
    size_t s = rq_parser.execute(&tmp[0], tmp.size());
    SYLAR_LOG_INFO(logger)<<"execute: "<<s;
    sylar::http::HttpRequest::ptr req = rq_parser.getData();
    req->dump(std::cout)<<std::endl; // 输出成流式
    //tmp.resize(tmp.size()-s);
    char* ptr;
    // memset(ptr, 0, atoi(req->getHeader("content-length").c_str()));
    std::cout<<"content-length: "<<atoi(req->getHeader("content-length").c_str())<<std::endl;
    std::cout<<tmp<<std::endl;

}

const char test_response_data[] = "HTTP/1.1 200 OK\r\n"
        "Date: Tue, 04 Jun 2019 15:43:56 GMT\r\n"
        "Server: Apache\r\n"
        "Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT\r\n"
        "ETag: \"51-47cf7e6ee8400\"\r\n"
        "Accept-Ranges: bytes\r\n"
        "Content-Length: 81\r\n"
        "Cache-Control: max-age=86400\r\n"
        "Expires: Wed, 05 Jun 2019 15:43:56 GMT\r\n"
        "Connection: Close\r\n"
        "Content-Type: text/html\r\n\r\n"
        "<html>\r\n"
        "<meta http-equiv=\"refresh\" content=\"0;url=http://www.baidu.com/\">\r\n"
        "</html>\r\n";

void test_response_parser() {
    sylar::http::HttpResponseParser parser;
    std::string tmp = test_response_data;
    size_t s = parser.execute(&tmp[0], tmp.size(), true);
    SYLAR_LOG_INFO(logger) << "execute rt=" << s
        << " has_error=" << parser.hasError()
        << " is_finished=" << parser.isFinished()
        << " total=" << tmp.size()
        << " content_length=" << parser.getContentLength()
        << " tmp[s]=" << tmp[s];

    tmp.resize(tmp.size() - s);

    SYLAR_LOG_INFO(logger) << parser.getData()->toString();
    SYLAR_LOG_INFO(logger) << tmp;
}

int main(){

    test_request_parser();
    //test_response_parser();

    return 0;
}